import { reqProducts, reqSearchProducts, reqUpdateStatus, reqCategoryName, reqAddProduct, reqUpdateProduct } from './service'


export default {
  namespace: 'product',
  state: {
    BASE_URL_IMG: 'http://120.55.193.14:5000/upload/',
    imgs: [],
    isUpdate: false, // 是否处于更新状态
    product: {}, // 选中商品
    productDetail: {}, // 当前选中商品详情
    addupdatePageNum: 1, // 添加和修改时,当前第几页
    addupdatePageSize: 3,// 添加和修改时,每页条数初始化
    detail: ''
  },
  effects: {
    // 获取商品分页列表
    *fetchProducts({ payload, callback }, { call }) {
      try {
        const result = yield call(reqProducts, {
          payload: {
            params: { ...payload }
          }
        })
        if (callback) callback(result)
      }catch (e) {
        console.log(e);
      }
    },

    // 获取商品搜索分页列表
    *fetchSearchProducts({ payload, callback }, { call }) {
      try {

        const { pageNum, pageSize, searchType, searchName } = payload
        const result = yield call(reqSearchProducts, {
          payload: {
            params: {
              pageNum,
              pageSize,
              [searchType]: searchName
            }
          }
        })
        if (callback) callback(result)
      }catch (e) {
        console.log(e);
      }
    },

    // 更新商品状态 上架/下架
    *fetchUpdateStatus({ payload, callback }, { call }) {
      try {
        const result = yield call(reqUpdateStatus, {
          payload: {
            data: {...payload}
          }
        })
        if (callback) callback(result)
      }catch (e) {
        console.log(e);
      }
    },

    // 根据分类id 获取分类名称
    *fetchCategoryName({ payload, callback }, { call }) {
      try {
        const result = yield call(reqCategoryName, {
          payload: {
            params: { ...payload }
          }
        })
        if (callback) callback(result)
      }catch (e) {
        console.log(e);
      }
    },

    // 添加/ 更新商品
    *fetchAddOrUpdateProduct({ payload, callback }, { call, select }) {
      try {
        const isUpdate = yield select(state => state.product.isUpdate)
        let result
        if (isUpdate)  {
          result = yield call(reqUpdateProduct, {
            payload: {
              data: { ...payload}
            }
          })
        }else {
          result = yield call(reqAddProduct, {
            payload: {
              data: { ...payload}
            }
          })
        }
        if (callback) callback(result)
      }catch (e) {
        console.log(e);
      }
    }

  },
  reducers: {
    save(state, {payload}: { payload: any }): any {
      return {
        ...state,
        ...payload
      }
    }
  }
}
